import { useEffect, useRef, useState } from "react";
import { connect } from "react-redux";
import { updateCollapse } from "@renderer/redux/modules/menu/action";
import { Graph } from "@antv/x6";
import { grid } from "../components/config/container";
import { addNodes } from "../components/hooks/useAddNode";
import nodes from "../components/config/data.json";
// 定义窗口大小类型
interface WindowSize {
	width: number;
	height: number;
}

// 定义容器组件的 props 类型
interface ContainerProps {
	isCollapse: boolean;
	updateCollapse: () => void;
}

const Container: React.FC<ContainerProps> = (props: any) => {
	const { isCollapse } = props;
	const containerRef = useRef<HTMLDivElement>(null);
	const graphRef = useRef<Graph | null>(null);

	// 初始状态设置为 undefined，这样可以知道窗口大小是否已加载
	const [windowSize, setWindowSize] = useState<WindowSize | undefined>(undefined);

	// 计算图表容器的样式
	const calculateContainerStyle = (size: WindowSize) => {
		const width = isCollapse ? size.width - 436 : size.width - 268;
		const height = size.height - 128;

		return {
			width: `${width}px`,
			height: `${height}px`,
			display: width > 0 && height > 0 ? "block" : "none"
		};
	};

	// 监听窗口大小变化
	useEffect(() => {
		// 获取初始窗口大小
		window.electronAPI.send("get-window-size");

		// 监听窗口大小变化事件
		const unsubscribe = window.electronAPI.on("window-size-changed", (size: WindowSize) => {
			setWindowSize(size);
		});

		// 组件卸载时移除监听
		return () => {
			if (typeof unsubscribe === "function") {
				unsubscribe();
			}
		};
	}, [isCollapse]); // 添加 isCollapse 依赖，当侧边栏状态变化时重新计算尺寸
	// 初始化图表
	useEffect(() => {
		if (!containerRef.current || !windowSize) return;

		// 如果图表已存在，更新容器
		if (graphRef.current) {
			graphRef.current.resize(isCollapse ? windowSize.width - 268 : windowSize.width - 436, windowSize.height - 128);
			return;
		}

		// 初始化新图表
		graphRef.current = new Graph({
			container: containerRef.current,
			background: { color: "#F2F7FA" },
			autoResize: true, // 开启自动调整
			panning: true,
			mousewheel: true,
			grid
		});
		addNodes(graphRef.current, nodes);
		// 组件卸载时销毁图表
		return () => {
			if (graphRef.current) {
				graphRef.current.dispose();
				graphRef.current = null;
			}
		};
	}, [windowSize, isCollapse]); // 添加 isCollapse 依赖，当侧边栏状态变化时重新渲染图表

	// 当侧边栏状态变化时重新计算图表尺寸
	useEffect(() => {
		if (!graphRef.current || !windowSize) return;
		graphRef.current.resize(isCollapse ? windowSize.width - 436 : windowSize.width - 268, windowSize.height - 128);
	}, [isCollapse, windowSize]);

	return (
		<div className="container-component">
			{windowSize ? (
				<div style={calculateContainerStyle(windowSize)}>
					<div ref={containerRef}></div>
				</div>
			) : (
				<div className="loading-indicator">加载中...</div>
			)}
		</div>
	);
};

const mapStateToProps = (state: any) => state.menu;
const mapDispatchToProps = { updateCollapse };
export default connect(mapStateToProps, mapDispatchToProps)(Container);
